<template>
  <a-tree-select
    v-model:value="value"
    v-model:searchValue="searchValue"
    multiple
    show-search
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="人员选择"
    allow-clear
    chech-stricty
    tree-checkable
    :tree-data="treeData"
    :field-names="{
      children: 'children',
      label: 'name',
      value: 'id',
    }"
    tree-node-filter-prop="name"
  >

    <template #title="{ name ,type}">
      <UserOutlined v-if="type == 1"/>
      <TeamOutlined v-else/>
      <b v-if="name === 'parent 1-1'" style="color: #08c">sss</b>
      <template v-else>
        <template
          v-for="(fragment, i) in name
            .toString()
            .split(new RegExp(`(?<=${searchValue})|(?=${searchValue})`, 'i'))"
        >
          <span
            v-if="fragment.toLowerCase() === searchValue.toLowerCase()"
            :key="i"
            style="color: #08c"
          >
            {{ fragment }}
          </span>
          <template v-else>{{ fragment }}</template>
        </template>
      </template>
    </template>
  </a-tree-select>
</template>

<script lang="ts" setup>

import {onMounted, ref, watch} from 'vue';
import {departUserTree} from "@/api/base/project/project"
import {message} from "ant-design-vue";
import {
  UserOutlined,
  TeamOutlined
} from '@ant-design/icons-vue';
interface Node {
  id: string;
  parentId: string;
  weight: number;
  name: string;
  type: number;
  children?: Node[];
}
const value = ref<string[]>();
let treeData = ref<Node[]>(); //部门人员树
const searchValue = ref('');
import {APP_USER} from '@/enums/cacheEnum';
import {Storage} from '@/utils/Storage';
const tenantid = ref(Storage.Get(APP_USER).tenantid);

// 查询部门人员树
const getTreeList = async () => {
  const {code, data} = await departUserTree(tenantid.value)
  if (code == 0) {
    // 处理数据，过滤掉没有type为1的子节点的节点
    treeData.value = filterNodesByType(data);
    // 在数据加载后立即处理，将type为1的节点的id设置为空
    console.log('树结点的值',treeData.value)
  } else {
    message.error('查询人员树失败')
  }
}
// 递归过滤函数，只保留那些自身或至少有一个子节点type为1的节点
function filterNodesByType(nodes: Node[]): Node[] {
  return nodes.filter(node => {
    // 如果节点自身type为1，直接返回true
    if (node.type === 1) {
      return true;
    }

    // 否则检查是否有子节点type为1
    if (node.children) {
      const filteredChildren = filterNodesByType(node.children);
      // 如果过滤后的子节点数组非空，则表明至少有一个子节点type为1
      if (filteredChildren.length > 0) {
        node.children = filteredChildren;
        return true;
      }
    }
    // 没有符合条件的子节点，返回false
    return false;
  });
}
// 清空选项
const allClear = () => {
  value.value = [];
}
// 主动暴露childMethod方法
defineExpose({ allClear });
// 传值给父组件
const emit = defineEmits(["change"])

watch(value, () => {
  emit('change',value.value) //将原change事件暴露
});

onMounted(() => {
  getTreeList()
})
defineOptions({
  name: 'DeptUserSelect',
});
</script>


<style scoped lang="less">

</style>
